<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;

use App\Http\Controllers\common\MyAgentController;
use App\Http\Controllers\Controller;
use DB;
class DeviceController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    // 主页
    public function getIndex(Request $request){
        $get['eui'] = $request -> input('eui','');
        $get['ag'] = $request -> input('ag','');
        $get['apply'] = '';
        switch ($request -> input('tp','')) {
            case '':
                $get['apply'] = '';
                break;
            case '烟感':
                $get['apply'] = 'smoke';
                break;
            case '电气':
                $get['apply'] = 'electric';
                break;
            case '呼救':
                $get['apply'] = 'call_help';
                break;
            case '红外':
                $get['apply'] = 'infrared';
                break;
            case '燃气':
                $get['apply'] = 'gas';
                break;

            default:
                break;
        }
        return view('admin.device.index',['toget'=>$get]);
    }
    // 主页Ajax获取请求的数据
    public function postToajax(Request $request){
        $agent = '';
        $data = '';
        $info = '';
        $get = array();
        $get['eui'] = $request->input('eui','');
        $get['area'] = $request->input('area','');
        $get['building'] = $request->input('building','');
        $get['room'] = $request->input('room','');
        $get['apply'] = $request->input('application','');
        /*代理商信息处理域*/
            //获取代理商id
            $agentId = $request->cookie('agentId');
            $get['ag'] = $request->input('ag',$agentId);
            //查询父级代理商path
            $path = DB::table('sa_agent') -> select('path') -> where(['id'=>$agentId]) -> first();
            $len = substr_count($path['path'],',');
            $agent = MyAgentController::allAgent($agentId);
            foreach ($agent as $k=>$v){
                $agent[$k]['agent_name'] = str_repeat('--',substr_count($v['path'],',')-$len)."&nbsp;&nbsp;".$v['agent_name'];
            }
        /*代理商信息处理域*/
        /*登录账号信息处理域*/
            //获取登录账号
            $adminId = $request -> cookie('adminId');
            //查询所选择账号的权限
            $res = DB::table('sa_admin') -> select('auth','scope') ->where('id','=',$adminId) -> first();
        /*登录账号信息处理域*/
        if($res['auth'] == 1){
            $data = DB::table('sa_'.$get['apply'].'_detector as rd')
                ->LeftJoin('sa_area as a','a.a_id','=','rd.a_id')
                ->LeftJoin('sa_building as b','b.b_id','=','rd.b_id')
                ->LeftJoin('sa_room as r','r.r_id','=','rd.r_id')
                ->LeftJoin('sa_model as m','m.tp_id','=','rd.model_id')
                ->LeftJoin('sa_type as t','t.id','=','rd.type_id')
                ->select('rd.id','rd.num','rd.eui','rd.status','r.r_id','r.r_name','b.b_id','b.b_name','a.a_id','a.a_name','rd.location','m.t_model','t.type','rd.add_time','agent_id')
                -> where(['agent_id'=>$get['ag']])
                -> where('rd.eui','like','%'.$get['eui'].'%')
                -> where('a.a_name','like','%'.$get['area'].'%')
                -> where('b.b_name','like','%'.$get['building'].'%')
                -> where('r.r_name','like','%'.$get['room'].'%')
                -> paginate(6);
        }else{
            $data = DB::table('sa_'.$get['apply'].'_detector as rd')
                ->LeftJoin('sa_area as a','a.a_id','=','rd.a_id')
                ->LeftJoin('sa_building as b','b.b_id','=','rd.b_id')
                ->LeftJoin('sa_room as r','r.r_id','=','rd.r_id')
                ->LeftJoin('sa_model as m','m.tp_id','=','rd.model_id')
                ->LeftJoin('sa_type as t','t.id','=','rd.type_id')
                ->select('rd.id','rd.num','rd.eui','rd.status','r.r_id','r.r_name','b.b_id','b.b_name','a.a_id','a.a_name','rd.location','m.t_model','t.type','rd.add_time','agent_id')
                -> where(['agent_id'=>$get['ag']])
                -> where('rd.eui','like','%'.$get['eui'].'%')
                -> where('a.a_name','like','%'.$get['area'].'%')
                -> where('b.b_name','like','%'.$get['building'].'%')
                -> where('r.r_name','like','%'.$get['room'].'%')
                -> whereIn('a.a_id',explode(',',$res['scope']))
                -> paginate(6);
        }

        $array =array();
        $array['current'] = $data -> currentPage();
        // $array['firstItem'] = $data -> firstItem();
        $array['lastItem'] = ceil(($data -> total())/6);
        $array['total'] = $data -> total();
        // dd($count);
        $info = $data -> all();
        foreach($info as $k=>$v){
            // 获取房间的负责人
            $r_uid = DB::table('sa_member_manager_area') -> select('mma_uid') ->where('mma_r_id','=',$v['r_id']) ->first();
            // 将拼接uid字符串拆分出成uid
            $r_user = explode(',',$r_uid['mma_uid']);
            $r_user_str = '';
            if($r_user[0]!=''){
                foreach($r_user as $val){
                    $r_res = DB::table('sa_member') -> select('username') -> where('uid','=',$val) -> first();
                    if($r_res!=''){
                        $r_user_str .= $r_res['username'].',';
                    }
                }
            }
            $info[$k]['r_user_str'] = substr($r_user_str,0,-1);
            // 获取建筑的负责人
            $b_uid = DB::table('sa_member_manager_area') -> select('mma_uid') -> where(['mma_b_id'=>$v['b_id'],'mma_r_id'=>0]) -> first();
            $b_user = explode(',',$b_uid['mma_uid']);
            //查询用户表得到用户名
            $b_user_str = '';
            if($b_user[0]!=''){
                foreach ($b_user as $val){
                    $b_res = DB::table('sa_member') -> select('username')-> where('uid','=',$val) -> first();
                    if($b_res){
                        $b_user_str .= $b_res['username'].',';
                    }
                }
            }
            $info[$k]['b_user_str'] = substr($b_user_str,0,-1);
            //获取区域负责人id
            $a_uid = DB::table('sa_member_manager_area') -> select('mma_uid') -> where(['mma_a_id'=>$v['a_id'],'mma_b_id'=>0,'mma_r_id'=>0]) -> first();
            $a_user = explode(',',$a_uid['mma_uid']);
            //查询用户表得到用户名
            $a_user_str = '';
            if($a_user[0]!=''){
                foreach ($a_user as $val){
                    $a_res = DB::table('sa_member') -> select('username')-> where('uid','=',$val) -> first();
                    if($a_res){
                        $a_user_str .= $a_res['username'].',';
                    }
                }
            }
            $info[$k]['a_user_str'] = substr($a_user_str,0,-1);
        }
        foreach ($info as $k=>$v){
            // $info[$k]['rd_add_time'] = date('Y-m-d H:i:s',$v['rd_add_time']);
            $info[$k]['add_time'] = date('Y-m-d H:i:s',$v['add_time']);
        }
        return view('admin.device.toajax',['agent'=>$agent,'info'=>$info,'request'=>$request->all(),'get'=>$get,'arr'=>$array]);
    }
    // 设备单独通知
    public function postStatus(Request $request){
        $old_status = $request->input('rd_status','1');
        if($old_status==1){
            $status = 0;
        }else{
            $status =1;
        }
        $id = $request->input('id');
        $apply = $request->input('apply');
        $res = DB::table('sa_'.$apply.'_detector') -> where('id',$id)->update(['status'=>$status]);
        if($res){
            echo $status;
        }else{
            echo $old_status;
        }
    }

    public function getCreate(Request $request){
        //获取登录id
        // $agentId = session('agentId');
        $agentId = $request->cookie('agentId');
        //查询设备类型表
        $type = DB::table('sa_type') -> get();
        /*登录账号信息处理域*/
            //获取登录账号
            $adminId = $request -> cookie('adminId');
            //查询所选择账号的权限
            $res = DB::table('sa_admin') -> select('auth','scope') ->where('id','=',$adminId) -> first();
        /*登录账号信息处理域*/
        //查询区域表
        if($res['auth'] == 1){
            $area = DB::table('sa_area') -> select('a_id','a_name') -> where(['a_agent_id'=>$agentId]) -> get();
        }else{
            $area = DB::table('sa_area') -> select('a_id','a_name') -> where(['a_agent_id'=>$agentId]) -> whereIn('a_id',explode(',',$res['scope'])) -> get();
        }
        //查询设备详情表
        $device = DB::table('sa_device') -> select('DevEUI') -> get();
        return view('admin.device.create',['type'=>$type,'area'=>$area,'device'=>$device]);
    }

    //添加绑定处理方法
    public function postCreate(Request $request){
        //获取ajax数据
        $eui = trim($request -> input('eui'));
        $r_id = $request -> input('rooms');
        $b_id = $request -> input('building');
        $a_id = $request -> input('area');
        $type_id = $request -> input('type');
        $model_id = $request -> input('model');
        $location = trim($request -> input('loc'));
        // $rd_agent_id = session('agentId');
        $agent_id = $request->cookie('agentId');
        $add_time = time();
        //查询设备详情表,获取参数
        $device = DB::table('sa_device') -> where('DevEUI','=',$eui) -> first();
        $DevAddr = $device['DevAddr'];
        $AppSKey = $device['AppSKey'];
        $NwkSKey = $device['NwkSKey'];
        //查询设备类型表
        $type = DB::table('sa_type') -> where('id','=',$type_id) -> select('app_eui') -> first();
        $AppEUI = $type['app_eui'];
        //插入lora 实例化lora类
        $lora = new LoraController();
        $info = $lora -> addTerminal($eui,$AppEUI,$DevAddr,$NwkSKey,$AppSKey);
        $info = json_decode($info,true);
        if($info['code'] == 1 || $info['info'] == "DevEUI or DevAddr exists!"){
            //查询烟感是否已存在
            $row = DB::table('sa_device') -> select('status')-> where('DevEUI','=',$eui) -> first();
            if($row['status'] == 1){
                //存在
                $data['status'] = '-3';
                $data['msg'] = '该设备在iot系统已被绑定,请勿重复绑定';
            }else{
                //不存在
                //插入绑定设备表
                $res = $this -> getDB($type_id);
                if(!empty($res)){
                    $insertId = DB::table($res['db']) -> insertGetId(compact('eui','a_id','b_id','r_id','location','type_id','model_id','agent_id','add_time'));
                    $num = $res['prefix'].str_pad($insertId, 6, "0", STR_PAD_LEFT);
                    DB::table($res['db']) -> where('id','=',$insertId) -> update(['num'=>$num]);
                }else{
                    $insertId = false;
                }
                if($insertId){
                    //修改sa_device表status字段
                    DB::table('sa_device') -> where('DevEUI','=',$eui) ->update(['status'=>1]);
                    $data['status'] = '1';
                    $data['msg'] = '设备绑定成功';
                }else{
                    $data['status'] = '-2';
                    $data['msg'] = '设备绑定失败';
                }
            }
        }else{
            $data['status'] = '-1';
            $data['msg'] = $info['info'];
        }
        echo json_encode($data);
    }

    //判断eui是否为空
    public function postCheck(Request $request){
        $eui = $request -> input('eui');
        //查询device表
        $res = DB::table('sa_device') -> select('status') -> where('DevEUI','=',$eui) -> first();
        if($res){
            if($res['status'] == 1){
                $data['status'] = '-1';
                $data['msg'] = '该设备已绑定,请前往编辑';
            }else{
                $data['status'] = '1';
                $data['msg'] = '可编辑';
            }
        }else{
            $data['status'] = '-1';
            $data['msg'] = '该设备不存在';
        }
        return json_encode($data);
    }

    //编辑绑定页面
    public function getEdit(Request $request){
        //获取数据
        $id = $request -> input('id');
        $app = $request -> input('app');
        //获取登录id
        // $agentId = session('agentId');
        $agentId = $request->cookie('agentId');
        $agent_id = $request -> input("ag",$agentId);
        //dd($agentId);
        /*登录账号信息处理域*/
            //获取登录账号
            $adminId = $request -> cookie('adminId');
            //查询所选择账号的权限
            $res = DB::table('sa_admin') -> select('auth','scope') ->where('id','=',$adminId) -> first();
        /*登录账号信息处理域*/
        //查询区域表
        if($res['auth'] == 1){
            $area = DB::table('sa_area') -> select('a_id','a_name') -> where(['a_agent_id'=>$agentId]) -> get();
        }else{
            $area = DB::table('sa_area') -> select('a_id','a_name') -> where(['a_agent_id'=>$agentId]) -> whereIn('a_id',explode(',',$res['scope'])) -> get();
        }
        //dd($area);
        //查询绑定设备表
        $data = DB::table('sa_'.$app.'_detector')
            -> LeftJoin('sa_building','sa_'.$app.'_detector.b_id','=','sa_building.b_id')
            -> select('sa_'.$app.'_detector.*','sa_building.b_name')
            -> where(['sa_'.$app.'_detector.id'=>$id])
            -> first();
        //dd($data);
        //查询建筑表
        $building = DB::table('sa_building') -> select('b_id','b_name') -> where(['b_a_id'=>$data['a_id']]) ->get();
        //查询位置表
        $room = DB::table('sa_room') -> select('r_id','r_name') -> where(['r_b_id'=>$data['b_id']]) -> get();
        //查询设备类型表
        $type = DB::table('sa_type') -> get();
        //查询设备型号表
        $model = DB::table('sa_model') -> select('tp_id','t_model') -> where(['t_type'=>$data['type_id']]) -> get();
        return view('admin.device.edit',['area'=>$area,'data'=>$data,'building'=>$building,'room'=>$room,'type'=>$type,'model'=>$model]);
    }

    //编辑绑定处理方法
    public function postEdit(Request $request){
        //获取ajax数据
        $id = $request -> input('rd_id');
        $eui = $request -> input('eui');
        $r_id = $request -> input('rooms');
        $b_id = $request -> input('building');
        $a_id = $request -> input('area');
        $location = $request -> input('loc');
        $type_id = $request -> input('type');
        $fri_type_id = $request -> input('fri_type');
        $model_id = $request -> input('model');
        $friDB = $this -> getDB($fri_type_id);
        $tarDB = $this -> getDB($type_id);
        $add_time = time();
        //dd([$id,$type_id,$fri_type_id]);
        //判断设备应用是否发生改变
        if($fri_type_id == $type_id){
            //设备应用没有发生改变
            if(!empty($friDB)){
                //修改绑定设备表
                $row = DB::table($friDB['db']) -> where(['id'=>$id]) -> update(compact('eui','a_id','b_id','r_id','location','type_id','model_id'));
                if($row){
                    $data['status'] = '1';
                    $data['msg'] = '设备绑定信息修改成功';
                }else{
                    $data['status'] = '-1';
                    $data['msg'] = '设备绑定信息修改失败';
                }
            }else{
                $data['status'] = '-1';
                $data['msg'] = '设备绑定信息修改失败';
            }
        }else{
            if(!empty($tarDB)){
                //删除lora上的设备
                $lora = new LoraController();
                $lora -> delTerminal($eui);
                //获取原绑定表代理商id
                $res = DB::table($friDB['db']) -> select('agent_id') -> where(['id'=>$id]) -> first();
                $agent_id = $res['agent_id'];
                //删除原绑定设备表
                DB::table($friDB['db']) -> where(['id'=>$id]) -> delete();
                //查询设备详情表,获取参数
                $dev = DB::table('sa_device') -> where('DevEUI','=',$eui) -> first();
                $DevAddr = $dev['DevAddr'];
                $AppSKey = $dev['AppSKey'];
                $NwkSKey = $dev['NwkSKey'];
                //查询设备类型表
                $type = DB::table('sa_type') -> where('id','=',$type_id) -> select('app_eui') -> first();
                $AppEUI = $type['app_eui'];
                //插入lora
                $lora -> addTerminal($eui,$AppEUI,$DevAddr,$NwkSKey,$AppSKey);
                //插入现绑定设备表
                $insertId = DB::table($tarDB['db']) -> insertGetId(compact('eui','a_id','b_id','r_id','location','type_id','model_id','agent_id','add_time'));
                $num = $tarDB['prefix'].str_pad($insertId, 6, "0", STR_PAD_LEFT);
                DB::table($tarDB['db']) -> where('id','=',$insertId) -> update(['num'=>$num]);
                if($insertId){
                    $data['status'] = '1';
                    $data['msg'] = '设备绑定信息修改成功';
                }else{
                    $data['status'] = '-1';
                    $data['msg'] = '设备绑定信息修改失败';
                }
            }else{
                $data['status'] = '-1';
                $data['msg'] = '设备绑定信息修改失败';
            }
        }
        echo json_encode($data);
    }

    //删除绑定
    public function postDel(Request $request){
        $rd_id = $request -> input('id');
        $apply = $request -> input('application');
        //查询绑定设备表
        $row = DB::table('sa_'.$apply.'_detector') -> select('eui') -> where(['id'=>$rd_id]) -> first();
        //删除Lora上的绑定设备
        $lora = new LoraController();
        $lora -> delTerminal($row['eui']);
        //删除本地记录
        $del = DB::table('sa_'.$apply.'_detector') -> where(['id'=>$rd_id]) -> delete();
        if($del){
            //修改sa_device表status字段
            DB::table('sa_device') -> where('DevEUI','=',$row['eui']) ->update(['status'=>0]);
            $data['status'] = '1';
            $data['msg'] = '删除成功';
        }else{
            $data['status'] = '-1';
            $data['msg'] = '本地记录未删除';
        }
        echo json_encode($data);
    }

    //类型与型号联动
    public function postGetmodel(Request $request){
        $typeId = $request -> input('typeId');
        //查询建筑表
        $room = DB::table('sa_model') -> select('tp_id','t_model') -> where(['t_type'=>$typeId]) -> get();
        echo json_encode($room);
    }

    // 日志
    public function getLog(Request $request)
    {

        $get['eui'] = $request->input('eui','');
        /*开始时间*/
        $start = $request->input('start','');
        if($start == ''){
            $get['start'] = strtotime('2000-06-16 00:00:00');
        }else{
            $get['start'] = strtotime(str_replace('+',' ',$start));
        }
        /*结束时间*/
        $end = $request->input('end','');
        if($end == ''){
            $get['end'] = strtotime(date('Y-m-d',time()))+24*60*60-1;
        }else{
            $get['end'] = strtotime(str_replace('+',' ',$end));
        }
        //dd([$start,$end]);
        $data = DB::table('sa_smok_data')
            -> where('DevEUI','like','%'.$get['eui'].'%')
            -> whereBetween('LaTime',[$get['start'],$get['end']])
            -> orderBy('LaTime','desc')
            -> paginate(10);
        return view('admin.device.trace',['data' => $data,'request' => $request -> all(),'get'=>$get]);
    }
    public function getDebug(Request $request)
    {

        $get['eui'] = $request->input('eui','');
        /*开始时间*/
        $start = $request->input('start','');
        if($start == ''){
            $get['start'] = strtotime('2000-06-16 00:00:00');
        }else{
            $get['start'] = strtotime(str_replace('+',' ',$start));
        }
        /*结束时间*/
        $end = $request->input('end','');
        if($end == ''){
            $get['end'] = strtotime(date('Y-m-d',time()))+24*60*60-1;
        }else{
            $get['end'] = strtotime(str_replace('+',' ',$end));
        }
        $data = DB::table('sa_smok_data')
            -> where('DevEUI','like','%'.$get['eui'].'%')
            -> whereBetween('LaTime',[$get['start'],$get['end']])
            -> orderBy('LaTime','desc')
            -> paginate(10);
        return view('admin.device.debug',['data' => $data,'request' => $request -> all(),'get'=>$get]);
    }

    public function getDevice(Request $request)
    {
        $get['eui'] = $request->input('eui','');
        $data = DB::table('sa_device') -> where('DevEUI','like','%'.$get['eui'].'%') -> paginate(10);
        // dd($data->total());
        return view('admin.device.device',['data' => $data,'request' => $request -> all(),'get'=>$get]);
    }

    //根据应用id获取数据库
    public function getDB($type_id){
        $res = [];
        switch ($type_id){
            case 2:
                $res['db'] = 'sa_smoke_detector';
                $res['prefix'] = 'SK';
                break;
            case 9:
                $res['db'] = 'sa_electric_detector';
                $res['prefix'] = 'ET';
                break;
            case 5:
                $res['db'] = 'sa_call_help_detector';
                $res['prefix'] = 'CH';
                break;
            case 3:
                $res['db'] = 'sa_infrared_detector';
                $res['prefix'] = 'IR';
                break;
            case 6:
                $res['db'] = 'sa_gas_detector';
                $res['prefix'] = 'GS';
                break;
            default:
                $res = [];
        }
        return $res;
    }

    public function getTest(){
        $edit['status'] = 1;
        $data = DB::table('sa_device') -> select('DevEUI') -> get();
        foreach($data as $v){
            $res = DB::table('sa_room_detector') -> select('rd_sd_eui') -> where('rd_sd_eui','=',$v['DevEUI']) -> first();
            if($res){
                DB::table('sa_device') -> where('DevEUI','=',$v['DevEUI']) -> update($edit);
            }
        }
    }
}
